
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { getAuthAxios } from '../lib/authAxios.js';
import { message } from 'antd';
import { GlobalVarListener, DOMObserver, FormDataCollector, IFrameHandler } from '../lib/components';

// 地址信息-核查校验
const RootComponent = () => {
  const [addressWarningObj, setAddressWarningObj] = useState(null);
  const [formData, setFormData] = useState({});
  const myAxios = getAuthAxios();

  useEffect(() => {
    setAddressWarningObj(window.getMyGlobalVar('warningObj'));
  }, []);

  // 处理全局变量变化
  const handleGlobalVarChange = (value, key) => {
    if (key === 'activeTabName' && value === '营业厅受理') {
      // 不再需要调用getDomPolling，由IFrameHandler组件处理
    } else if (key === 'warningObj') {
      setAddressWarningObj(value);
    }
  };

  // 处理iframe准备就绪
  const handleIFrameReady = (iframeDoc, iframe) => {
    // 高亮必填项
    highlightRequiredFields(iframeDoc);
    
    // 设置上传观察器
    observeUpload(iframeDoc);
  };

  // 高亮必填项
  const highlightRequiredFields = (iframeDoc) => {
    const requireList = iframeDoc.querySelectorAll('.is-required>label');
    requireList.forEach(i => i.style.backgroundColor = 'rgb(252,241,118)');
  };

  // 处理表单数据收集
  const handleFormDataCollected = (data) => {
    setFormData(data);
  };

  // 观察上传组件
  const observeUpload = (iframeDoc) => {
    // 保留原有的observeUpload逻辑
  };

  // 检查地址
  const checkAddress = (val1, val2, inputDOM) => {
    myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcAreaWide/list', { "streetName": val1, "communityName": val2 })
      .then(response => {
        console.log('数据已成功发送:', response.data);
        if (response.data.data.list.length > 0) {
          console.log('通过');
          message.success('用电地址校验通过');
        } else {
          message.warning('用电地址校验不通过');
          inputDOM.style.backgroundColor = 'rgba(255,0,0,0.2)';
          saveWarningData(addressWarningObj);
        }
      })
      .catch(error => {
        console.error('发送数据失败:', error);
        message.warning("由于网络问题，用电地址未能校核");
      });
  };

  // 保存预警数据
  const saveWarningData = (saveWarningData) => {
    myAxios.post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcRemindMsg/addBatch', saveWarningData)
      .then(response => {
        console.log('数据已成功发送:', response.data);
      })
      .catch(error => {
        console.error('发送数据失败:', error);
      });
  };

  // 处理地址
  const handleAddress = (str, inputDOM) => {
    const addressRegex = /^(.+?省)|(.+?市)(.+?[市区县])(.+?街道|.+?镇|.+?乡)(.+?村委会|.+?居委会|.+?社区|.+?村)(.*)$/;
    const match = str.match(addressRegex);
    if (match) {
      const [, province, city, district, street, committee, detail] = match;
      return checkAddress(street, committee, inputDOM);
    }
    return false;
  };

  return (
    <>
      {/* 使用GlobalVarListener组件监听全局变量变化 */}
      <GlobalVarListener 
        onChange={handleGlobalVarChange} 
      />
      
      {/* 使用IFrameHandler组件处理iframe */}
      <IFrameHandler
        containerSelector=".main-container-view"
        onIFrameReady={handleIFrameReady}
        displayFilter="block"
        targetIndex={2}
      />
      
      {/* 使用FormDataCollector组件收集表单数据 */}
      <DOMObserver
        target=".main-container-view iframe:nth-child(3)"
        callback={(iframe) => {
          if (iframe && iframe.contentDocument) {
            const iframeDoc = iframe.contentDocument;
            setTimeout(() => {
              <FormDataCollector
                container={iframeDoc}
                onDataCollected={handleFormDataCollected}
              />
            }, 1000);
          }
        }}
      />
    </>
  );
};

const init = () => {
  const container = document.createElement('div');
  document.body.appendChild(container);
  const root = ReactDOM.createRoot(container);
  root.render(<RootComponent />);
};

init();
